package com.service.impl;

import com.mapper.AreaMapper;
import com.pojo.Area;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: AreaService
 * @Description:
 * @Version: v1.0.0
 * @Author: Fu Hao
 * @Date: 2021/6/26 0026 上午 11:08
 * Modification History:
 * Date           Author      Version     Description
 * -------------------------------------------------------------
 * 2021/6/26 0026        Fu Hao      v1.0.0         创建
 */
@Service
public class AreaService implements com.service.AreaService {



    @Autowired
    private AreaMapper areaMapper;

    @Override
    public boolean save(Area child) {
        return areaMapper.save(child);
    }

    @Override
    public List<Area> selectDisList(String pid) {
        return areaMapper.selectDisList(pid);
    }

    @Override
    public List<Area> selectListAll() {
        List<Area> regions = areaMapper.selectListAll();
        List<Area> tree = new ArrayList<>();
        regions.forEach(item->{
            if (item.getParentCode().equals("0")){
                recursionFn(regions, item);  //递归列表
                tree.add(item);
            }
        });
        return tree;
    }

    private void recursionFn(List<Area> list, Area region){
        // 得到子节点列表
        List<Area> childList = getChildList(list, region);
        region.setChildrenList(childList);
        childList.forEach(item->{
            if(hasChild(list,item)){
                //判断是否有子节点
                recursionFn(list, item);
            }
        });

    }
    private List<Area> getChildList(List<Area> list, Area region){
        List<Area> tlist = new ArrayList<Area>();
        list.forEach(item->{
            if(item.getParentCode().equals(region.getAdCode())){
                tlist.add(item);
            }
        });
        return tlist;
    }

    private boolean hasChild(List<Area> list, Area region)
    {
        return getChildList(list, region).size() > 0 ? true : false;
    }


}
